package diandiansong.library.ui.base;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import diandiansong.library.R;
import diandiansong.library.utils.Logger;


public abstract class BaseListFragment<E> extends BaseFrag implements SwipeRefreshLayout.OnRefreshListener, OnItemClickListener, OnScrollListener {

    protected Logger logger = Logger.getLogger();

    /**
     * 普通状态
     */
    public static final int STATE_NONE = 0;
    /**
     * 正在刷新
     */
    public static final int STATE_REFRESH = 1;
    /**
     * 正在加载更多
     */
    public static final int STATE_LOADMORE = 2;

    /**
     * 所有数据加载完成
     */
    public static final int STATE_NOMORE = 3;


    public int mState = STATE_NONE;

    protected SwipeRefreshLayout mSwipeRefreshLayout;
    protected ListView mListView;
    protected TextView mTvTip;

    protected BaseListAdapter<E> mAdapter;

    /**
     * viewCreated 后调用
     *
     * @param rootView framentView
     */
    public abstract void initView(View rootView);

    /**
     * 初始化adapter
     *
     * @return adapter
     */
    protected abstract BaseListAdapter<E> initAdapter();

    /**
     * 其他操作
     */
    protected abstract void initData();

    /**
     * 刷新, no refresh icon
     */
    protected abstract void refresh();

    /**
     * 滑到底部时调用
     */
    protected abstract void loadMore();


    /**
     * 允许子类重写，替换布局
     * <p/>
     * must have @id/swiperefreshlayout @id/listview
     *
     * @return layoutId
     */
    protected int getLayoutId() {
        return R.layout.arn_base_list_fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(getLayoutId(), container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshlayout);
        mListView = (ListView) view.findViewById(R.id.listview);
        mTvTip = (TextView) view.findViewById(R.id.tv_tips);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        //        mSwipeRefreshLayout.setColorSchemeColors();

        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(this);

        initView(view);

        mAdapter = initAdapter();

        mListView.setAdapter(mAdapter);

        initData();
    }

    protected View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        return LayoutInflater.from(getActivity()).inflate(resource, root, attachToRoot);
    }

    protected E getItem(int position) {
        return mAdapter.getItem(position);
    }

    protected void notifyDataSetChanged() {
        mAdapter.notifyDataSetChanged();
    }


    /**
     * 下拉刷新，有刷新图标效果
     */
    @Override
    public void onRefresh() {
        if (mState == STATE_REFRESH) {
            return;
        }
        // 设置顶部正在刷新
        mListView.setSelection(0);

        //设置顶部正在加载的状态
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);
                }
            });
            // 防止多次重复刷新
            mSwipeRefreshLayout.setEnabled(false);
        }

        mState = STATE_REFRESH;
        refresh();
    }

    /**
     * 设置顶部加载完毕的状态
     */
    private void setUILoadFinish() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                    mSwipeRefreshLayout.setEnabled(true);
                }
            });
        }
    }

    /**
     * 完成刷新
     */
    protected void onLoadFinishHasMore(boolean hasMore) {
        setUILoadFinish();
        if (hasMore) {
            mState = STATE_NONE;
            mAdapter.setState(BaseListAdapter.STATE_LOAD_MORE);
        } else {
            mState = STATE_NOMORE;
            mAdapter.setState(BaseListAdapter.STATE_NONE);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 完成刷新
     */
    protected void onLoadFinishHasMore() {
        onLoadFinishHasMore(true);
    }

    /**
     * 完成刷新
     */
    protected void onLoadFinishNoMore() {
        onLoadFinishHasMore(false);
    }

    @Override
    public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //数据为空，不处理滚动事件，只支持刷新
        if (mAdapter == null || mAdapter.getCount() == 0) {
            return;
        }
        // 数据已经全部加载，或数据为空时，或正在加载，或正在刷新，不处理滚动事件
        if (mState != STATE_NONE) {
            return;
        }
        switch (scrollState) {
            // 当不滚动时
            case OnScrollListener.SCROLL_STATE_IDLE: {
                // 判断滚动到底部
                if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                    if (mAdapter.getState() == BaseListAdapter.STATE_LOAD_MORE) {
                        mState = STATE_LOADMORE;
                        loadMore();
                    }
                }
            }
            break;
        }
    }

    protected int mPage;

    public void handleData(List<E> list) {
//        if (list == null || list.size() == 0) {
//            onLoadFinishNoMore();
//
//        } else {
//            if (mPage == 1) {
//                mAdapter.setData(list);
//
//            } else {
//                mAdapter.addAll(list);
//            }
//            onLoadFinishHasMore();
//
//            if (list.size() < Api.PAGE_SIZE - 2) {//如果数量太少会导致加载更多一直转圈
//                loadMore();
//            }
//        }
    }

    public void toast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }
}
